package com.foxit.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.log4j.Logger;
import org.json.JSONObject;

public class URLConnectionHelper {
	private static final Logger log =Logger.getLogger(URLConnectionHelper.class);
	/**
	 * 向指定URL发�?POST方法的请�?
	 * @param <JSONObject>
	 * 
	 * @param url
	 *            发�?请求的URL
	 * @param params
	 *            请求参数，请求参数应该是name1=value1&name2=value2的形式�?
	 * @return URL�?��表远程资源的响应
	 */
	public static InputStream sendPostAndGetStream(String url, JSONObject jsonParam) {
		PrintWriter out = null;
		BufferedReader in = null;
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连�?
			HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
			// 设置通用的请求属�?
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			conn.setRequestProperty("Content-Type","application/json");   
			conn.setConnectTimeout(30000); 
			conn.setReadTimeout(30000);
			// 发�?POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发�?请求参数
			out.write(jsonParam.toString());
			// flush输出流的缓冲
			out.flush();
			out.close();
			out = null;
			int httpResult = conn.getResponseCode();
			if(httpResult ==HttpURLConnection.HTTP_OK)
			{
				return conn.getInputStream();
			}
			else
				return null;
		} catch (Exception e) {
			log.error(e);
		}
		// 使用finally块来关闭输出流�?输入�?
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				log.error(ex);
			}
		}
		return null;
	}
	
	
	public static int getHttpResponseCode(URLConnection connection) throws IOException
	{
		if ( connection instanceof HttpURLConnection)
		{
		   HttpURLConnection httpConnection = (HttpURLConnection) connection;
		   return httpConnection.getResponseCode();
		}
		else
		{
			HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
			return httpsConnection.getResponseCode();
		}
	}

	/**
	 * 向指定URL发�?POST方法的请�?
	 * @param <JSONObject>
	 * 
	 * @param url
	 *            发�?请求的URL
	 * @param params
	 *            请求参数，请求参数应该是name1=value1&name2=value2的形式�?
	 * @return URL�?��表远程资源的响应
	 */
	public static String sendPost(String url, JSONObject jsonParam) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连�?
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属�?
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			conn.setRequestProperty("Content-Type","application/json;charset=UTF-8");   
			conn.setConnectTimeout(30000); 
			conn.setReadTimeout(30000);
			// 发�?POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发�?请求参数
			String params = jsonParam.toString();//URLEncoder.encode(jsonParam.toString(),"UTF-8");
			out.write(params);
			// flush输出流的缓冲
			out.flush();
			out.close();
			out = null;
			int httpResult = getHttpResponseCode(conn);
			if(httpResult ==HttpURLConnection.HTTP_OK)
			{
				in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
				String line;
				while ((line = in.readLine()) != null) {
					result += "\n" + line;
				}
			}
			else
				return "";
		} catch (Exception e) {
			log.error(e);
		}
		// 使用finally块来关闭输出流�?输入�?
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				log.error(ex);
			}
		}
		return result;
	}
	public static String sendPost(String url, String gsonParam) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连�?
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属�?
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			conn.setRequestProperty("Content-Type","application/json;charset=UTF-8");   
			conn.setConnectTimeout(30000); 
			conn.setReadTimeout(30000);
			// 发�?POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发�?请求参数
			String params = gsonParam;//URLEncoder.encode(jsonParam.toString(),"UTF-8");
			out.write(params);
			// flush输出流的缓冲
			out.flush();
			out.close();
			out = null;
			int httpResult = getHttpResponseCode(conn);
			if(httpResult ==HttpURLConnection.HTTP_OK)
			{
				in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
				String line;
				while ((line = in.readLine()) != null) {
					result += "\n" + line;
				}
			}
			else
				return "";
		} catch (Exception e) {
			log.error(e);
		}
		// 使用finally块来关闭输出流�?输入�?
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				log.error(ex);
			}
		}
		return result;
	}
	public static InputStream downloadFile(String url)
	{
		try {
			
			 // Create a new trust manager that trust all certificates
			/*TrustManager[] trustAllCerts = new TrustManager[]{
			    new X509TrustManager() {
			        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
			            return null;
			        }
			        public void checkClientTrusted(
			            java.security.cert.X509Certificate[] certs, String authType) {
			        }
			        public void checkServerTrusted(
			            java.security.cert.X509Certificate[] certs, String authType) {
			        }
			    }
			};
			
				// Activate the new trust manager
				try {
				    SSLContext sc = SSLContext.getInstance("SSL");
				    sc.init(null, trustAllCerts, new java.security.SecureRandom());
				    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
				} catch (Exception e) {
				}
			 
			javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
				    new javax.net.ssl.HostnameVerifier(){
				 
				        public boolean verify(String hostname,
				                javax.net.ssl.SSLSession sslSession) {
				            return true;
				        }
				    });*/
			URL realUrl = new URL(url);
			URLConnection conn = realUrl.openConnection();
			conn.setConnectTimeout(30000); 
			conn.setReadTimeout(30000);
			int responseCode = getHttpResponseCode(conn);
			if (responseCode == HttpsURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_PARTIAL) {
				return conn.getInputStream();
			}else if(responseCode == HttpURLConnection.HTTP_MOVED_TEMP){
				String location = conn.getHeaderField("Location");  
				return URLConnectionHelper.downloadFile(location);
			}
			else
			{
				return null;
			}
		} catch (Exception e) {
			log.error(e);
			return null;
		}
		finally {
		}
	}
}